package com.jshare.tiezi.use.fenye;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.jshare.dao.TieziDAO;
import com.jshare.dao.TzReplyDAO;
import com.jshare.entity.Tiezi;

public class PageInfoDaoImpl implements PageInfoDao {
	private TieziDAO tieziDao;
	private TzReplyDAO tzReplyDao;
	
	public TzReplyDAO getTzReplyDao() {
		return tzReplyDao;
	}

	public void setTzReplyDao(TzReplyDAO tzReplyDao) {
		this.tzReplyDao = tzReplyDao;
	}

	public TieziDAO getTieziDao() {
		return tieziDao;
	}

	public void setTieziDao(TieziDAO tieziDao) {
		this.tieziDao = tieziDao;
	}

	public PageInfo getPageInfo(int curPage, int pageSize, String sql) {
		List list = tieziDao.findAll();
		List resultlist = new ArrayList();
		PageInfo info = new PageInfo();
		int allRecords = list.size();
		int startPos = (curPage-1)*pageSize;
		int pageCount = 0;
		if(allRecords<pageSize){
			pageCount = 1;
			pageSize = allRecords;
		}else{
			if(allRecords%pageSize==0){
				pageCount = allRecords/pageSize;
			}else{
				pageCount = allRecords/pageSize + 1;
			}
		}
		resultlist = tieziDao.findByStartPos(startPos, pageSize);
		info.setAllRecords(allRecords);
		info.setStartPos(startPos);
		info.setPageSize(pageSize);
		info.setCurPage(curPage); 
		info.setPageCount(pageCount);
		info.setSql(sql);
		info.setResultlist(resultlist);
		return info;
	}
	
	public PageInfo getPageInfo(int curPage, int pageSize, Integer tiezi_id) {
		PageInfo info = new PageInfo();
		List resultlist = new ArrayList();
		String propertyName = "tiezi";
		Tiezi tie = tieziDao.findById(tiezi_id);
		int allRec = 1;
		int pageCount = 1;
		int startPos = 0;
		List list = tzReplyDao.findByProperty("tiezi", tie);
		if(list==null){
			resultlist.add(tie);
		}else if(1+list.size()<=pageSize){
			resultlist.add(tie);
			allRec = 1 + list.size();
			pageSize = 1 + list.size();
			for(int i = 0 ; i < list.size();i++){
				resultlist.add(list.get(i));
			}
		}else if(1+list.size()>pageSize){
			if((1+list.size())%pageSize==0){
				pageCount = (1+list.size()) / pageSize;
			}else{
				pageCount = (1+list.size()) / pageSize + 1;
			}
			if(curPage==1){
				resultlist.add(tie);
				List newlist = tzReplyDao.findByStartPos(propertyName, tie, startPos, pageSize-1);
				for(int i = 0 ; i < newlist.size();i++){
					resultlist.add(newlist.get(i));
				}
			}else{
				startPos = (curPage-1)*pageSize - 1;
				List newlist = tzReplyDao.findByStartPos(propertyName, tie, startPos, pageSize);
				for(int i = 0 ; i < newlist.size();i++){
					resultlist.add(newlist.get(i));
				}
			}
		}
		
		info.setAllRecords(allRec);
		info.setCurPage(curPage);
		info.setPageCount(pageCount);
		info.setPageSize(pageSize);
		info.setResultlist(resultlist);
		info.setStartPos(startPos);
		return info;
	}

}
